<template>
  <div class="work-order-list">
    <CommonHeader
      :title="title"
      :is-show-back="true"
      class="header-top"
    />

    <CommonMain>
      <template>
        <van-pull-refresh
          v-model="refreshing"
          :disabled="isRefreshDisable"
          @refresh="onRefresh"
        >
          <div class="bg">
            <material-detailItem :item-obj="infoData" @printDialog="printDialog"></material-detailItem>
          </div>
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              v-for="(item, index) in batchList"
              :key="index"
            >
              <batch-list :status="infoData.state" :index="index" :formData="item" @checkChange="checkChange" @numChange="numChange" @batchDelete="batchDelete" @printDialog="printDialog"></batch-list>
            </div>
          </van-list>
          <!-- <div v-if="!loading && this.infoData.saleMaterialDetailEntityList.length == 0" class="no-data">暂无数据</div> -->
        </van-pull-refresh>
        <Toasts v-show="toastShow" />
      </template>
    </CommonMain>
    <div class="footer">
      <van-popover
        v-model="showPopover"
        trigger="click"
        :actions="actions"
        @select="onSelect"
        placement="top-start"
      >
        <template #reference>
          <div class="footer-more" v-if="infoData.state === 0 || infoData.state === 1">
            <div class="footer-more-l">
              <img src="@/assets/images/more.png" alt="" />
            </div>
            <div class="footer-more-r">更多</div>
          </div>
        </template>
      </van-popover>

      <van-button color="#548AF1"  v-if="infoData.state === 0 || infoData.state === 1" @click="toBacth" plain>新增</van-button>
      <van-button color="#548AF1" @click="submit">提交</van-button>
    </div>
    <img src="@/assets/images/allocation/scan.png"  class="scan-img" @click="scanChange" v-draggable/>
    <!-- 打印 -->
    <print v-if="printShow" :isShowPrintNum="printShow" :currentItem="currentItem" :activeTab="activeTab" @handleConfirmPrint="handleConfirmPrint" @handleCancelPrint="handleCancelPrint"></print>
    <!-- 扫码新增批次弹窗 -->
    <material-dialog
      v-if="materialShow"
      :isLock="true"
      :show="materialShow"
      :warehouseCode="infoData.warehouseCode"
      :barCode="materialShowBarcode"
      :material-name="infoData.materialFields.name"
      :material-code="infoData.code || infoData.materialFields.code"
      :sku-obj="skuData"
      :orderNumber="infoData.inventoryOrderNumber"
      @handleCancel="materialHandleCancel"
      @handleConfirm="materialHandleConfirm"
    >
    </material-dialog>
  </div>
</template>
<script>
import materialDialog from "@/components/materialDialog"
import print from "../allocationDetail/components/print.vue"
import materialDetailItem from "./components/materialDetailItem.vue";
import batchList from "./components/batchList.vue";
import CommonHeader from "@/components/CommonHeader/index.vue";
import CommonMain from "@/components/CommonMain/index.vue";
import { Popover, Dialog,Toast } from "vant";
import Toasts from '@/components/Toast'
import { materialDetailsInfoList ,deleteMaterialDetails, updateMaterialDetails,materialDetailsByMaterialId} from "@/api/inventory";

export default {
  data() {
    return {
      skuData:{},
      title: "物料明细（批次管理）",
      infoData: {},
      actions: [{ text: "批量删除", className: "delete" }],
      showPopover: false,
      selecLsist: [],
      loading: false,
      isRefreshDisable: false,
      refreshing: false,
      finished: false,
      searchParams: {
        compositeSearch:'',
        current: 0,
        size: 10,
      },
      // 滚动与下拉冲突
      scrollTop: 0,
      toastShow:false,
      choseIds:[],
      batchList:[],
      isBatchMag:false,
      printShow:false,
      currentItem:{},
      isScan: false, //是否点击了扫码
      materialShow: false,
      materialShowBarcode: "",
      activeTab:1
    };
  },
  components: {
    materialDialog,
    print,
    CommonHeader,
    materialDetailItem,
    CommonMain,
    batchList,
    Toasts,
    [Toast.name]:Toast,
    [Popover.name]: Popover,
    [Dialog.Component.name]: Dialog.Component,
  },
  watch: {
    scrollTop(newval) {
      if (newval > 0) {
        this.isRefreshDisable = true;
      } else {
        this.isRefreshDisable = false;
      }
    },
    // 'infoData.saleMaterialDetailEntityList':{
    //   handler(n,o){
    //     const counts = n.map(item=>item.realNum)
    //     const sum = counts.reduce((accumulator, currentValue) => {
    //       return accumulator + Number(currentValue);
    //     }, 0);
    //     this.infoData.actualNum = sum % 1 === 0 ? sum: sum.toFixed(2)
    //   },
    //   immediate: false,
    //   deep:true
    // }
  },
  created(){
    this.getHeader()
  },
  mounted () {
    const that = this
    // PDA扫码
    window['QrcodeMsg'] = res => {
      if (res) {
        if(this.loading){
          return
        }
        console.log(res, 'ScanCodeMsg这是首页')
        that.isScan = true;
        that.materialShowBarcode = res
        that.searchParams.compositeSearch = res
        that.getInfo()
      }
    }
    // 扫码枪扫码
    window['ScanCodeMsg'] = res => {
      if (res) {
        if(this.loading){
          return
        }
        console.log(res,'ScanCodeMsg这是首页')
        that.isScan = true;
        that.materialShowBarcode = res
        that.searchParams.compositeSearch = res
        that.getInfo()
      }
    }
  },
  methods: {
    materialHandleCancel(){
      this.materialShow = false
      this.isScan = false
      // 取消搜索
      this.materialShowBarcode = ""
      this.searchParams.compositeSearch = ""
      this.onRefresh()
    },
    async materialHandleConfirm(paramsData,done){
      await this.materialSubmit(paramsData)
      done()
      this.isScan = false
      this.materialShow = false
      
    },
    async materialSubmit(paramsData){
      const {form,records} = paramsData || {}
      const param = records.map((item) => {
        return {
          skuId: item.skuId,
          skuCode: item.materialFields
            ? item.materialFields.skuEntity?.skuCode
            : "",
          skuName: item.materialFields
            ? item.materialFields.skuEntity?.skuName
            : "",
          barCode: item.barCode,
          materialQuality: form.materialQuality || "1",
          isNewAdd:  true ,
          realNum: form.realNum,
          stockMaterialId: this.$route.query.id,
          remark: '',
          inventoryDetailId: item.inventoryDetailId,
          orderNo:this.$route.query.orderNo
        };
      });
      const result = await updateMaterialDetails(param);
      const {code,message,data} = result.data
      if(code == 200){
        this.materialShowBarcode = ""
        this.searchParams.compositeSearch = ""
        this.getHeader()
        this.onRefresh()
      }else{
        Toast(message)
      }
    },
    materialDialogShow() {
      this.materialShow = true;
    },
    handleConfirmPrint(){
      this.printShow = false
    },
    handleCancelPrint(){
      this.printShow = false
    },
    printDialog(data,type){
      this.printShow = true
      this.currentItem = data
      this.activeTab = type
    },
    // 手动拉起相机
    scanChange(){
      if(this.loading){
        return
      }
      const that = this
      that.isScan = true;
      if(process.env.NODE_ENV === 'development'){
        // this.handleScanData("PO20230611002")
        this.searchParams.compositeSearch = "CK2023090400030-62-44"
        this.materialShowBarcode = "CK2023090400030-62-44";
        this.getInfo()
      } else {
        window.flutter_inappwebview.callHandler("qrCode").then((res) => {
          if (res) {
            console.log(res, "qrCode");
            this.searchParams.compositeSearch = res
            this.materialShowBarcode = res;
            this.getInfo()
          }
        });
      }
    },
    async getHeader(){
      const id = this.$route.query.id;
      const {
        data: { data: infoData, code, message },
      } = await materialDetailsInfoList({ materialId: id });
      console.log("result", infoData);
      infoData.orderNo =
        this.$route.query.orderNo || localStorage.getItem("orderNo");
      infoData.isToggle = false;
      this.infoData = infoData;
      this.skuData = {
        skuCode:infoData.skuCode,
        skuName:infoData.skuName,
        skuId:infoData.skuId
      }
      if(this.infoData.state === 0 || this.infoData.state === 1){
        this.actions = [{ text: "批量删除", className: "delete" }]
      }
      this.title = this.infoData.materialFields.isBatchMag ? '物料明细（批次管理）': '物料明细（非批次管理）'
    },
    async getInfo() {
      const id = this.$route.query.id;
      this.loading = true;
      this.finished = false;

      //物料明细列表
      const params = {...this.searchParams, id: id}
      const {
        data: { data: {records,total} },
      } = await materialDetailsByMaterialId(params)
      records.map(item=>{
        if(item.stockInventoryDetailEntity){
          item.stockInventoryDetailEntity.materialQualityName = item.stockInventoryDetailEntity?.materialQuality == '1' ? '合格':'不合格'
        }else{
          item.stockInventoryDetailEntity = {
            materialFields:{}
          }
        }
      })
      if(this.searchParams.current > 1){
        this.batchList = [...this.batchList,...records];
      }else {
        this.batchList = records
      }
      if (this.infoData.state != 2) {
        if (this.isScan && this.infoData.materialFields.isBatchMag) {
          if (this.batchList.length == 0) {
            this.materialDialogShow();
          } else {
            this.isScan = false;
          }
        }
      }
      if(this.batchList.length >= total){
        this.finished = true;
      }
      this.loading = false;
      this.refreshing = false;
    },
    async numChange(data){
      await this.updateMaterialDetails([data])
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.finished = false;
      this.list = [];
      this.searchParams.current = 1;
      this.getInfo();
    },
    // 加载更多
    onLoad() {
      if (this.finished) {
        return;
      }
      console.log("滚到了底部");
      this.searchParams.current += 1;
      this.getInfo();
    },
    onSelect(action) {
      console.log(action)
      if(action.text == "批量删除"){
        if(this.choseIds.length>0){
          this.deleteMaterialDetails()
        }
      }

    },
    toBacth() {
      const selectMaterialData = {
        warehouseCode:this.$route.query.warehouseCode,
        code: this.infoData.materialFields.code,
        name: this.infoData.materialFields.name,
        isBatchMag: this.infoData.materialFields.isBatchMag,
        skuId: this.infoData.skuId
      };
      this.$router.push({
        path: "/batch",
        query:{
          id: this.$route.query.id,
          materialInfo: JSON.stringify(selectMaterialData),
          warehouseCode:this.$route.query.warehouseCode,
          Oid: this.$route.query.Oid
        }

      });
    },
    checkChange(){
      const datas = this.batchList.filter(item=>item.checked)
      this.choseIds = datas.map(item=>item.stockMaterialDetailId)
      console.log( datas, this.choseIds)
    },
    batchDelete(data){
       this.choseIds = data
       this.isScan = false
       this.deleteMaterialDetails()
    },
    deleteMaterialDetails() {
      Dialog.confirm({
        title: "删除",
        message: "确认删除此批次",
        confirmButtonColor:"#548AF1"
      })
        .then(async () => {
          // on confirm
          await deleteMaterialDetails(this.choseIds)
          this.getInfo();
           this.getHeader()
        })
    },
    async submit(){
      await this.updateMaterialDetails(this.batchList)
      this.$router.push({
        path:"/allocationDetail",
        query:{
          id:this.$route.query.Oid,
          orderNo:this.$route.query.orderNo
        }
      })
    },
    updateMaterialDetails(data) {
      return new Promise(async (resolve, reject) => {
        const {
          data: { code },
        } = await updateMaterialDetails(data);
        if (code == 200) {
          Toast.success("提交成功");
          this.getHeader()
          resolve();
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "../../assets/css/common.scss";
.scan-img{
  position: fixed;
  bottom: 80px;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}
.main-content {
  background-image: linear-gradient(
    180deg,
    #548af1 0%,
    #84afff 72%,
    #ffffff 100%
  );
  background-size: 100% 100px;
  background-repeat: no-repeat;
}
.work-order-list {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f6f6f6;
  .van-pull-refresh {
    height: 100%;
    overflow: scroll;
    /deep/ .van-pull-refresh__track {
      // overflow: scroll;
    }
    .van-list {
      height: 100%;
      // overflow: scroll;
    }
    .no-data {
      height: 100%;
      font-size: 14px;
      display: flex;
      justify-content: center;
      color: #c7c6c6;
      padding-top: 30px;
    }
  }
}
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  // bottom: constant(safe-area-inset-bottom); /* iOS */
  // bottom: env(safe-area-inset-bottom); /* Android */
  width: 100%;
  height: 65px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  .van-button {
    width: 6.5rem;
    box-shadow: 0px 4px 8px 1px rgba(8, 9, 29, 0.1);
    border-radius: 4px 4px 4px 4px;
  }
  .footer-more {
    display: flex;
    align-items: center;

    .footer-more-l {
      display: flex;
      align-items: center;
      margin-right: 10px;
    }
    .footer-more-r {
      font-size: 16px;
      font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      font-weight: 400;
      color: #666666;
    }
  }
}
</style>
<style lang="scss">
.van-popover__action {
  &.delete {
    color: #f94741 !important;
  }
}
</style>
